<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <!-- 最后一块石头的重量 -->
    <script>
      var lastStoneWeightII = function (stones) {
        let sum = stones.reduce((a, b) => a + b)
        let target = Math.floor(sum / 2)
        let dp = new Array(target + 1).fill(0)
        //将石头尽量分成重量相等的两份，一份是dp[target]的最大重量，另一份是sum-dp[target]
        for (let i = 0; i < stones.length; i++) {
          for (let j = target; j >= stones[i]; j--) {
            dp[j] = Math.max(dp[j], dp[j - stones[i]] + stones[i])
          }
        }
        return sum - dp[target] - dp[target]
      }
      console.log(lastStoneWeightII([2, 7, 4, 1, 8, 1]))
    </script>
  </body>
</html>
